import axios from 'axios';
import {
    API_URL
} from '../constant';
import {
    authService
} from './auth.service';

class HttpService {
    constructor(baseUrl = API_URL) {
        this.client = axios.create({
            baseURL: baseUrl,
            timeout: 30000,
            headers: {
                'Content-Type': 'application/json',
            },
        });

        this.client.interceptors.request.use(
            (config) => {
                if (config.requireAuth !== false && authService.getToken()) {
                    config.headers['Authorization'] = `Bearer ${authService.getToken()}`;
                }
                return config;
            },
            (error) => Promise.reject(error)
        );

        this.client.interceptors.response.use(
            (response) => response.data,
            (error) => {
                let message = "Network error, please try again.";
                let errors = null;

                if (error.response) {
                    if (error.response.status === 401) {
                        authService.logout();
                        window.location.reload();
                    } else {
                        message = `${error.response.status} - ${error.response.data?.message || error.message}`;
                        errors = error.response.data?.errors || null;
                    }
                }

                const customError = new Error(message);
                customError.errors = errors;
                return Promise.reject(customError);
            }
        );
    }

    async get(endpoint, config = {}) {
        return this.client.get(endpoint, config);
    }

    async post(endpoint, data, config = {}) {
        return this.client.post(endpoint, data, config);
    }

    async put(endpoint, data, config = {}) {
        return this.client.put(endpoint, data, config);
    }

    async delete(endpoint, config = {}) {
        return this.client.delete(endpoint, config);
    }
}

const httpService = new HttpService();
export default httpService;